﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace PIMS.Utils
{
    /// <summary>
    /// XML序列化与反序列化助手
    /// </summary>
    public class XmlHelper
    {     
        /// <summary>
        /// 将对象序列化为xml文件且保存
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="t">对象</param>
        /// <param name="filePathAndName">xml存放路径和名称</param>
        /// <returns>True:表示成功</returns>
        public static bool ObjectToXmlFile<T>(T t, string filePathAndName) where T : class
        {
            if (t == null || string.IsNullOrEmpty(filePathAndName)) return false;
 
            bool success = false;
            try
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T));
                using (FileStream stream = new FileStream(filePathAndName, FileMode.OpenOrCreate))
                {
                    formatter.Serialize(stream, t);
                    success = true;
                }
            }
            catch (Exception ex)
            {
                success = false;
                Console.WriteLine(ex.Message+ex.StackTrace);
                throw new Exception(ex.Message);
            }
            return success;
        }
 
        /// <summary>
        /// 将对象序列化为xml字符串
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="t">对象</param>
        public static string ObjectToXmlStr<T>(T t) where T : class
        {
            if (t == null) return null;
 
            try
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T));
                using (MemoryStream stream = new MemoryStream())
                {
                    formatter.Serialize(stream, t);
                    string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                    return result;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
 
        }
 
        /// <summary>
        /// 将xml文件反序列化为对象
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="t">对象</param>
        /// <param name="filePathAndName">xml文件的路径和名称</param>
        /// <returns>对象</returns>
        public static T XmlFileToObject<T>(string filePathAndName) where T : class
        {
            if (string.IsNullOrEmpty(filePathAndName)) return null;
 
            try
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T));
                using (FileStream stream = new FileStream(filePathAndName, FileMode.OpenOrCreate))
                {
                    XmlReader xmlReader = new XmlTextReader(stream);
                    T result = formatter.Deserialize(xmlReader) as T;
                    return result;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
 
        }
 
        /// <summary>
        /// 将xml字符串反序列化为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="xmlStr">xml文件字符串</param>
        /// <returns></returns>
        public static T XmlStrToObject<T>(string xmlStr) where T : class
        {
            if (string.IsNullOrEmpty(xmlStr)) return null;
 
            try
            {
                using (StringReader sr = new StringReader(xmlStr))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary> 
        /// Xml字符串格式验证 
        /// <param name="xmlString">Xml字符串</param> 
        /// <returns></returns> 
        public static bool IsValidXml(string xmlString)
        {
            try
            {
                // 创建XmlDocument对象
                XmlDocument xmlDoc = new XmlDocument();
                // 加载xml字符串
                xmlDoc.LoadXml(xmlString);
                // 如果没有异常，则说明xml字符串是有效的
                return true;
            }
            catch (XmlException ex)
            {
                // 如果有异常，则说明xml字符串是无效的 
                //Data at the root level is invalid. Line 1, position 1.
                return false;
            }
        }

        /// <summary> 
        /// Xml字符串格式验证 
        /// <param name="xmlString">Xml字符串</param> 
        /// <returns></returns> 
        public static bool IsValidXmlFile(string xmlFile)
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.IgnoreComments = true;
                XmlReader reader = XmlReader.Create(xmlFile, settings);
                xmlDocument.Load(reader);
                reader.Close();

                return true;
            }
            catch (XmlException ex)
            {
                // 如果有异常，则说明xml字符串是无效的 
                return false;
            }
        }

    }
}
